package media;


import java.util.logging.Level;
import java.util.logging.Logger;
import javax.media.*;
import javax.media.protocol.*;
import javax.media.format.*;
import java.io.File;
import java.io.IOException;
import media.soundUtils;
import voip.SIPProperty;


public class RTPtransmitter{
	private MediaLocator mediaLocator = null;
	private DataSink dataSink = null;
	private Processor mediaProcessor = null;
	private String mediaName = "";
	private double fileDuration = 0;
	
	public boolean transmitFinished = false;
	
	private static final Format[] FORMATS = new Format[]{
		new AudioFormat(AudioFormat.ULAW_RTP)
		};
	
	private static final ContentDescriptor CONTENT_DESCRIPTOR =
		new ContentDescriptor(ContentDescriptor.RAW_RTP);
	
	public RTPtransmitter(String caller, String outPort, String fileName){
		String location = "rtp://" + caller + ":" + outPort + "/audio";
		mediaLocator = new MediaLocator(location);
		mediaName = fileName;
	}
	
	public void startTransmitting() throws IOException {
		mediaProcessor.start();
		dataSink.open();
		dataSink.start();
	}

	public void stopTransmitting(){
		try {
			dataSink.stop();
			dataSink.close();
			mediaProcessor.stop();
			mediaProcessor.close();
			System.out.println("stopped...");
			transmitFinished = true;
			
		} catch (IOException ex) {
			Logger.getLogger(RTPtransmitter.class.getName()).log(Level.SEVERE, null, ex);
		}
	}
	
	public void setDataSource(DataSource ds) throws IOException,
	NoProcessorException, CannotRealizeException, NoDataSinkException {


		mediaProcessor = Manager.createRealizedProcessor(
				new ProcessorModel(ds, FORMATS, CONTENT_DESCRIPTOR));


		dataSink = Manager.createDataSink(mediaProcessor.getDataOutput(),
				mediaLocator);
	}

	
	public void transmit() {
		
		DataSource source = null;

		try {
			
			System.out.println("-> Created media locator");
			

			File mediaFile = new File(mediaName);
			if(!mediaFile.exists()){
				mediaFile = new File(SIPProperty.default_message);
			}
			
			source = Manager.createDataSource(new MediaLocator(mediaFile.toURI().toURL()));

			fileDuration = soundUtils.getLength(mediaName);
			
			setDataSource(source);
			System.out.println("-> Set the data source " + mediaName + " on the transmitter");
			startTransmitting();
			System.out.println("-> Transmitting...");

			try {
			    Thread.currentThread();
				Thread.sleep((int)(fileDuration*1000 + 500));
			} catch (InterruptedException ie) {
				ie.printStackTrace();
			}
			System.out.println("-> Stopping...");
			stopTransmitting();

		} catch (Throwable t) {
			t.printStackTrace();
		}
	}

}
